import 'dart:async';
import 'package:aqua_plunge/model/payment.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

import '../controller/UserController.dart';
import '../dao/purchase_dao.dart';

class InAppPurchaseService {
  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  bool available = false;
  late StreamSubscription<List<PurchaseDetails>> _subscription;

  Payment? _payment; // 用于保存当前要购买的 Payment 对象
  final UserController _userController = Get.find<UserController>();

  InAppPurchaseService() {
    _subscription = _inAppPurchase.purchaseStream.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (Object error) {
      // 处理错误
      print("Purchase Stream Error: $error");
    });

    _initialize(); // 初始化
  }

  void _initialize() async {
    available = await _inAppPurchase.isAvailable();
    if (!available) {
      ToastUtils.showCenter('In-app purchase not available');
    }
  }

  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) {
    for (var purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        // 处理等待状态
        ToastUtils.showCenter('Purchase is pending...');
      } else if (purchaseDetails.status == PurchaseStatus.purchased) {
        if (purchaseDetails.pendingCompletePurchase) {
          _completePurchase(purchaseDetails);
        }
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        // 处理取消
        _payment = null;
        _completePurchase(purchaseDetails);
        ToastUtils.showCenter('Purchase was canceled.');
      } else if (purchaseDetails.status == PurchaseStatus.error) {
        // 处理错误
        ToastUtils.showCenter('Purchase error: ${purchaseDetails.error?.message}');
      }
    }
  }

  Future<void> _completePurchase(PurchaseDetails purchaseDetails) async {
    await _inAppPurchase.completePurchase(purchaseDetails);
    // 调用支付检查接口
    if (_payment != null) {
      await PurchaseDao.paymentCheck(
        _payment!.orderNo??'',
        purchaseDetails.verificationData.serverVerificationData,
        purchaseDetails.purchaseID ?? '',
            () {
          ToastUtils.showCenter('Recharge success!');
          _userController.updateInfo();
        },
      );
    }
  }

  Future<void> buyProduct(Payment payment, Function fail) async {
    available = await _inAppPurchase.isAvailable();
    if (!available) {
      fail();
      return;
    }
    _payment = payment; // 保存当前支付信息
    Set<String> productIds = {_payment?.goodsCode ?? ''}; // 传入要购买的产品ID
    final response = await _inAppPurchase.queryProductDetails(productIds);

    if (response.error == null && response.productDetails.isNotEmpty) {
      final PurchaseParam purchaseParam =
      PurchaseParam(productDetails: response.productDetails.first);
      _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam);
    } else {
      fail(); // 查询产品失败时调用失败回调
    }
  }
}